package com.lanhe.order.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lanhe.common.constant.Constants;
import com.lanhe.common.constant.HttpStatus;
import com.lanhe.common.core.domain.entity.LhMemberBase;
import com.lanhe.common.exception.ServiceException;
import com.lanhe.common.utils.DateUtils;
import com.lanhe.common.utils.StringUtils;
import com.lanhe.common.utils.duoyou.DuoYouUtil;
import com.lanhe.member.service.ILhMemberBaseService;
import com.lanhe.order.domain.LhOrdersDuoyou;
import com.lanhe.order.domain.LhOrdersDuoyouLog;
import com.lanhe.order.domain.LhOrdersPool;
import com.lanhe.order.domain.dto.LhOrdersDuoyouDto;
import com.lanhe.order.mapper.LhOrdersDuoyouMapper;
import com.lanhe.order.service.ILhOrdersDuoyouLogService;
import com.lanhe.order.service.ILhOrdersDuoyouService;
import com.lanhe.order.service.ILhOrdersPoolService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.*;

/**
 * (LhOrdersDuoyou)表服务实现类
 *
 * @author zhanggl
 * @since 2023-12-11 09:58:47
 */
@Service
@Slf4j
public class LhOrdersDuoyouServiceImpl extends ServiceImpl<LhOrdersDuoyouMapper, LhOrdersDuoyou> implements ILhOrdersDuoyouService {

	@Autowired
	private ILhMemberBaseService memberBaseService;

	@Autowired
	private LhOrdersDuoyouMapper ordersDuoyouMapper;

	@Autowired
	private ILhOrdersPoolService ordersPoolService;

	@Resource
	private ILhOrdersDuoyouLogService lhOrdersDuoyouLogService;

	@Resource
	private DuoYouUtil duoYouUtil;

	private final PlatformTransactionManager transactionManager;

	@Autowired
	public LhOrdersDuoyouServiceImpl(PlatformTransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}

	/**
	 * 多游订单类别
	 *
	 * @param ordersHaoka 实体
	 * @return java.util.List<com.lanhe.order.domain.LhOrdersHaoka>
	 * @author zhanggl
	 * @date 2023/12/28
	 */
	@Override
	public List<LhOrdersDuoyou> selectOrdersList(LhOrdersDuoyou ordersHaoka) {
		LambdaQueryWrapper<LhOrdersDuoyou> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(LhOrdersDuoyou::getMemberId, ordersHaoka.getMemberId());
		return ordersDuoyouMapper.selectList(queryWrapper);
	}

	/**
	 * 增加多游订单
	 *
	 * @param ordersDuoyou 实体
	 * @author zhanggl
	 * @date 2023/12/11
	 */
	@Override
	public void insertOrdersDuoyou(LhOrdersDuoyouDto ordersDuoyou) {

		// 增加日志信息-返回日志ID
		Long ordersDuoyouLogId = addOrdersDuoyouLog(ordersDuoyou);
		log.info("LhOrdersDuoyouServiceImpl--->add ordersDuoyouLogId：【{}】", ordersDuoyouLogId);
		ordersDuoyou.setOrdersDuoyouLogId(ordersDuoyouLogId);
		if (StringUtils.isBlank(ordersDuoyou.getSign())) {
			updateOrdersDuoyouLog(ordersDuoyou.getOrdersDuoyouLogId(), Constants.GeneralIntType.TWO,"签名为为空");
			throw new ServiceException("缺少必要条件,签名为为空", HttpStatus.ERROR);
		}

		if (StringUtils.isBlank(ordersDuoyou.getOrder_id())) {
			updateOrdersDuoyouLog(ordersDuoyou.getOrdersDuoyouLogId(), Constants.GeneralIntType.TWO,"用户USERID为空");
			throw new ServiceException("缺少必要条件,用户USERID为空", HttpStatus.ERROR);
		}

		Map<String, String> signMap = getStringStringMap(ordersDuoyou);
		String sign = null;
		try {
			sign = duoYouUtil.getSign(signMap);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		log.info("LhOrdersDuoyouServiceImpl--->add 多游收回调加密后签名：【{}】", sign);
		if (!ordersDuoyou.getSign().equals(sign)) {
			updateOrdersDuoyouLog(ordersDuoyou.getOrdersDuoyouLogId(), Constants.GeneralIntType.TWO,"签名sign错误");
			throw new ServiceException("签名sign错误", HttpStatus.ERROR);
		}

		LhMemberBase memberBase = memberBaseService.getUserByUserKey(ordersDuoyou.getUser_id());
		if (ObjectUtil.isNull(memberBase)) {
			updateOrdersDuoyouLog(ordersDuoyou.getOrdersDuoyouLogId(), Constants.GeneralIntType.TWO,"用户未匹配");
			throw new ServiceException("用户未匹配到", HttpStatus.ERROR);
		}

		LambdaQueryWrapper<LhOrdersDuoyou> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(LhOrdersDuoyou::getOrderId, ordersDuoyou.getOrder_id());
		queryWrapper.eq(LhOrdersDuoyou::getUserId, ordersDuoyou.getUser_id());

		if (ordersDuoyouMapper.selectCount(queryWrapper) <= 0) {
			TransactionStatus transactionStatus = transactionManager.getTransaction(new DefaultTransactionDefinition());
			try {

				// 增加主订单
				LhOrdersDuoyou orders = new LhOrdersDuoyou();
				orders.setOrderId(ordersDuoyou.getOrder_id());
				orders.setAdvertId(Long.parseLong(ordersDuoyou.getAdvert_id()));
				orders.setAdvertName(ordersDuoyou.getAdvert_name());
				orders.setCreated(Long.parseLong(ordersDuoyou.getCreated()));
				orders.setMediaIncome(new BigDecimal(ordersDuoyou.getMedia_income()));
				orders.setMemberIncome(new BigDecimal(ordersDuoyou.getMember_income()));
				orders.setMediaId(ordersDuoyou.getMedia_id());
				orders.setUserId(ordersDuoyou.getUser_id());
				orders.setMemberId(memberBase.getMemberId());
				orders.setDeviceId(ordersDuoyou.getDevice_id());
				orders.setContent(ordersDuoyou.getContent());
				orders.setExtra(ordersDuoyou.getExtra());
				orders.setCreateTime(new Date());
				ordersDuoyouMapper.insert(orders);

				if (ObjectUtil.isNotNull(memberBase)) {

					// 获取当前日期
					LocalDate currentDate = LocalDate.now();

					// 获取当前日期-周
					WeekFields weekFields = WeekFields.of(Locale.getDefault());
					int currentWeek = currentDate.get(weekFields.weekOfWeekBasedYear());

					// 增加汇总表数据
					LhOrdersPool ordersPool = new LhOrdersPool();
					ordersPool.setOrderNumber(DateUtils.generateOrderCode());
					ordersPool.setMemberId(memberBase.getMemberId());
					ordersPool.setOrigin(Constants.ORDERS_ORIGIN_DUOYOU);
					ordersPool.setOrderId(orders.getOrdersDuoyouId());
					ordersPool.setRevenueType(Constants.ORDERS_REVENUE_TYPE_0);
					ordersPool.setProductName(orders.getAdvertName());
					ordersPool.setProductIntroduction(orders.getContent());
					ordersPool.setYear(currentDate.getYear());
					ordersPool.setMonthly(Integer.valueOf(currentDate.getYear() + "" + currentDate.getMonthValue()));
					ordersPool.setWeekly(currentWeek);
					ordersPool.setDaily(Integer.valueOf(currentDate.getYear() + "" + currentDate.getMonthValue() + "" + currentDate.getDayOfMonth()));
					ordersPool.setMediaAmount(orders.getMediaIncome());
					ordersPool.setAmount(orders.getMemberIncome());
					ordersPool.setStatus(Constants.GeneralIntType.ONE.toString());
					ordersPoolService.insertOrdersPool(ordersPool);

					// 更新会员收益
					memberBaseService.updateMemberBenefits(ordersPool);

					// 更新日志
					updateOrdersDuoyouLog(ordersDuoyou.getOrdersDuoyouLogId(), Constants.GeneralIntType.ONE,"正常");
				}

				// 提交订单
				transactionManager.commit(transactionStatus);

			} catch (Exception e) {
				transactionManager.rollback(transactionStatus);
				updateOrdersDuoyouLog(ordersDuoyou.getOrdersDuoyouLogId(), Constants.GeneralIntType.TWO,"异常->" + e.getMessage());
				throw new ServiceException("处理异常=>" + e.getMessage());
			}

		} else {
			updateOrdersDuoyouLog(ordersDuoyou.getOrdersDuoyouLogId(), Constants.GeneralIntType.TWO,"订单已经存在,请勿重复处理");
		}
	}


	/**
	 * 新增日志信息
	 *
	 * @param ordersDuoyou 实体对象
	 * @return 日志ID
	 * @author zhanggl
	 * @date 2023年12月11日15:38:19
	 */
	public Long addOrdersDuoyouLog(LhOrdersDuoyouDto ordersDuoyou) {

		LhOrdersDuoyouLog ordersDuoyouLog = new LhOrdersDuoyouLog();
		ordersDuoyouLog.setOrderId(ordersDuoyou.getOrder_id());
		ordersDuoyouLog.setAdvertId(ordersDuoyou.getAdvert_id());
		ordersDuoyouLog.setAdvertName(ordersDuoyou.getAdvert_name());
		ordersDuoyouLog.setCreated(ordersDuoyou.getCreated());
		ordersDuoyouLog.setMediaIncome(ordersDuoyou.getMedia_income());
		ordersDuoyouLog.setMemberIncome(ordersDuoyou.getMember_income());
		ordersDuoyouLog.setMediaId(ordersDuoyou.getMedia_id());
		ordersDuoyouLog.setUserId(ordersDuoyou.getUser_id());
		ordersDuoyouLog.setDeviceId(ordersDuoyou.getDevice_id());
		ordersDuoyouLog.setContent(ordersDuoyou.getContent());
		ordersDuoyouLog.setExtra(ordersDuoyou.getExtra());
		ordersDuoyouLog.setSign(ordersDuoyou.getSign());
		ordersDuoyouLog.setFromTxt(JSON.toJSONString(ordersDuoyou));
		ordersDuoyouLog.setStatus(Constants.GeneralIntType.ZERO);

		// 增加回调日志记录
		return lhOrdersDuoyouLogService.insertOrdersDuoyouLog(ordersDuoyouLog);
	}

	/**
	 * 更新日志信息
	 *
	 * @param orderDuoyouLogId ID
	 * @param status           状态
	 * @param reason           备注
	 * @author zhanggl
	 * @date 2023年12月27日10:50:05
	 */
	private void updateOrdersDuoyouLog(Long orderDuoyouLogId, Integer status, String reason) {
		LhOrdersDuoyouLog ordersDuoyouLog = new LhOrdersDuoyouLog();
		ordersDuoyouLog.setOrdersDuoyouLogId(orderDuoyouLogId);
		ordersDuoyouLog.setStatus(status);
		ordersDuoyouLog.setReason(reason);
		lhOrdersDuoyouLogService.updateOrdersDuoyouLog(ordersDuoyouLog);
	}

	/**
	 * 获取签名
	 *
	 * @param ordersDuoyou 实体
	 * @return java.util.Map<java.lang.String, java.lang.String>
	 * @author zhanggl
	 * @date 2023/12/11
	 */
	private static Map<String, String> getStringStringMap(LhOrdersDuoyouDto ordersDuoyou) {
		Map<String, String> signMap = new HashMap<>();
		signMap.put("order_id", ordersDuoyou.getOrder_id());
		signMap.put("advert_id", ordersDuoyou.getAdvert_id());
		signMap.put("advert_name", ordersDuoyou.getAdvert_name());
		signMap.put("created", ordersDuoyou.getCreated());
		signMap.put("media_income", ordersDuoyou.getMedia_income());
		signMap.put("member_income", ordersDuoyou.getMember_income());
		signMap.put("user_id", ordersDuoyou.getUser_id());
		signMap.put("device_id", ordersDuoyou.getDevice_id());
		signMap.put("content", ordersDuoyou.getContent());
		return signMap;
	}
}

